package forum.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import forum.dao.TopicDao;
import forum.model.ReplyListResult;
import forum.model.User;
import forum.service.ReplyService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author haomin
 * @date 2022/07/01 17:05
 **/

@WebServlet("/reply-list.json")
public class ReplyListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String tidString = req.getParameter("tid");
        int tid = Integer.parseInt(tidString);

        User currentUser = null;
        HttpSession session = req.getSession(false);
        if(session != null){
            currentUser = (User)session.getAttribute("currentUser");
        }

        // 浏览一次回帖页面，浏览次数加1
        new TopicDao().update(tid);

        ReplyService replyService = new ReplyService();
        ReplyListResult result = replyService.replyListResult(currentUser,tid);
        result.tid = tid;


        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(jsonString);
    }
}